<template>
  <div class="notice">
    <div class="plan">
      <span class="data"></span>
      <div class="cursor" style="opacity: 1"></div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, onMounted, onUnmounted, ref, watch } from 'vue'
const props = defineProps({
  commonArr: {
    type: Array,
    default: () => []
  }
})
let next = ref(true)
onUnmounted(() => {
  noticeTimer && clearInterval(noticeTimer.value)
})
let noticeTimer = ref(null)
onMounted(() => {
  cursorOpacity()
  noticeTimer.value = setInterval(() => {
    let index = Math.ceil(Math.random() * (props.commonArr.length - 1))
    if (next.value) {
      textCrease(props.commonArr[index])
    }
  }, 5000)
})
const cursorOpacity = () => {
  let c = document.querySelector('.cursor')
  setInterval(() => {
    let opacity = c.style.opacity
    c.style.opacity = opacity === '0' ? '1' : '0'
  }, 600)
}
const textCrease = text => {
  next.value = false
  let a = document.querySelector('.data')
  let currentIndex = 0
  let increaseTimer = setInterval(() => {
    if (a.textContent.length < text.length) {
      a.textContent = a.textContent + text.charAt(currentIndex)
      currentIndex++
    } else {
      clearInterval(increaseTimer)
      let setTimer = setTimeout(() => {
        let desceaseTimer = setInterval(() => {
          a.textContent = a.textContent.substring(0, a.textContent.length - 1)
          if (a.textContent.length === 0) {
            next.value = true
            clearInterval(desceaseTimer)
            clearTimeout(setTimer)
          }
        }, 100)
      }, 3000)
    }
  }, 200)
}
</script>

<style lang="scss" scoped>
.notice {
  text-align: left;
  position: absolute;
  left: 8px;
  top: 430px;
  color: #e47470;
}
.plan {
  display: inline-block;
  font-size: 1px;
  width: 250px;
}
.cursor {
  display: inline-block;
  width: 2px;
  height: 19px;
  background-color: #333;
  vertical-align: sub;
  font-size: 0;
}
.data {
  display: inline;
  font-size: 16px;
}
</style>